<?php
namespace app\api\service;
use think\Controller;
use think\Db;
use Des3\DES3;

class Common extends Controller {
    static protected $err_code = 0;
    // 发送短信接口
    static public function send_note($param) {
        if(!isset($param['phone']) ||
            !isset($param['type'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        // 启动事务
        //Db::startTrans();
        try{
            // 验证手机号码
            /*调用验证器 验证数据*/
            $validate = validate('Member');
            if(!$validate->scene('phone')->check(['phone' => $param['phone']])){
                self::$err_code = $validate->getError();
                throw new \Exception($validate->getError());
            }

            // 组装短信参数
            $str = '';
            $phone = $param['phone'];
            $mobiles[] = $phone;
            $str .= 'mobiles=' . json_encode($mobiles);

            $type = $param['type'];
            if (isset($param['model']) && $param['model'] > 0) {
                $model = $param['model'];
            } else {
                $model = 3029411;
                $params[] = $code = rand(1000, 9999);
                $params[] = 6;
                $param['params'] = json_encode($params);
            }
            $str .='&templateid='. $model;

            if (isset($param['params']) && !empty($param['params'])) {
                $str .='&params='. $param['params'];
            }


            $url = 'https://api.netease.im/sms/sendtemplate.action';
            $headers = array();
            $time = time();
            $AppKey = '49375d56619322b7f929cc3c13c62195';
            $AppSecret  = '3980db0ae0d5';
            $Nonce = md5(date('YmdHis')).rand(10000, 99999);
            $CheckSum = sha1($AppSecret . $Nonce . $time);
            array_push($headers, "AppKey:$AppKey");
            array_push($headers, "Nonce:$Nonce");
            array_push($headers, "CurTime:$time");
            array_push($headers, "CheckSum:$CheckSum");

            $curl = curl_init();
 
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($curl, CURLOPT_HEADER, true);

            curl_setopt ( $curl, CURLOPT_URL, $url);
            curl_setopt ( $curl, CURLOPT_POST, 1 );
            curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
            curl_setopt ( $curl, CURLOPT_POSTFIELDS, $str);
            
            if (1 == strpos("$".$url, "https://"))
            {
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            }
            $rs =  curl_exec($curl);
            //file_put_contents('mob_note_code.text', $rs . " \n " . date('Y-m-d H:i:s') . " \n ", FILE_APPEND);
            //调用短信接口

            $rs = substr($rs, strpos($rs, '{'));
            $rs_str = $rs;
            $rs = json_decode($rs, true);
            if ($rs['code'] == 200 && $model == 3029411) {
                //发送成功 写入数据库
                Db::table('mob_note_code')->insertGetId(['code' => $code, 'add_time' => time(), 'phone' => $phone, 'type' => $type]);
            } else {
                self::$err_code = 400128;
                throw new \Exception($rs_str);
            }
            //Db::commit();

            return ['code'=>200,  'msg'=> 'SUCCESS'];

        } catch (\Exception $e) {
            // 回滚事务
            //Db::rollback();
            return ['code'=>self::$err_code,'msg'=> $e->getMessage() ];
        }

    }

    // 验证短信验证码接口
    static public function check_note_code($param) {
        if(!isset($param['phone']) ||
            !isset($param['type']) ||
            !isset($param['code'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        try{
            $phone = $param['phone'];
            $type = $param['type'];
            $code = $param['code'];

            $check_code = check_note_code($code, $phone, $type);
            if($check_code['code'] != 200) {
                self::$err_code = $check_code['code'];
                throw new \Exception('FAULT');
            }

//            if($type == 3) { // 如果是找回密码， 做个标记， 方面后面实际修改密码的时候验证身份， 有效期10分钟
//                cookie('retrieve_password_' . $phone, '1', 600);
//            }
//
            if(isset($param['action']) && $param['action'] == 'weixin') { // 微信验证验证码
                cookie($code, '1', 600);
            }

            return ['code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }
    }

    // 获取省市区街道地址接口
    static public function get_region($param) {
        if(!isset($param['region_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
            $regions = Db::table('mob_region')->where('parent_id', $param['region_id'])->select();
            return ['data' => $regions, 'code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }
    }

    // 设置负责区域接口 ----- 待定
    static public function set_duty_area($param) {
        if(!isset($param['member_id']) || !isset($param['member_type']) || !isset($param['province'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
    }

    // 获取服务器时间接口
    static public function get_time($param) {
        return ['data' => ['time' => time()], 'code' => 200, 'msg' => 'SUCCESS'];
    }

    // pj 获取服务项目
    static public function get_items($param) {
        try{
            $items = Db::table('mob_server_items')->select();
            return ['data' => $items, 'code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }
    }
//    // 编辑实名认证
//    static public function update_certification($param) {
//        if(!isset($param['member_id']) || !isset($param['id_card_in_hand']) || !isset($param['id_card_front']) || !isset($param['id_card_verso']) ||
//            !isset($param['member_type']) ||
//            !isset($param['card_no']) ||
//            !isset($param['proposer'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
//
//        // 启动事务
//        Db::startTrans();
//        try{
//            $data = [
//                'proposer' => $param['proposer']
//                ,'card_no' => $param['card_no']
//                ,'audit_status' => 1
//                ,'id_card_in_hand' => $param['id_card_in_hand']
//                ,'id_card_front' => $param['id_card_front']
//                ,'id_card_verso' => $param['id_card_verso']
//            ];
//
//            switch ($param['member_type']) {
//                case 0:
//                    $model = 'member';
//                    break;
//                case 1:
//                    $model = 'repair';
//                    break;
//                case 2:
//                    $model = 'dealer';
//                    break;
//                case 3:
//                    $model = 'partner';
//                    break;
//                default:
//                    self::$err_code = 400078;
//                    throw new \Exception('FAULT');
//                    break;
//            }
//
//            Db::table('mob_'.$model)->where('member_id', $param['member_id'])->update($data);
//            Db::commit();
//            return ['code'=>200,'msg'=> 'SUCCESS'];
//
//        } catch (\Exception $e) {
//            // 回滚事务
//            Db::rollback();
//            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
//        }
//    }

    // 编辑用户基本信息
//    static public function update_member_role_info($param) {
//        if(!isset($param['member_id']) || !isset($param['type'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
//
//        // 启动事务
//        Db::startTrans();
//        try{
//            $where['member_id'] = $param['member_id'];
//            $where['type'] = $param['type'];
//            $user_data = Db::table('mob_member_role_info')->where($where)->find();
//            $data = [];
//            if (isset($param['qq']) && !empty($param['qq'])) {
//                $data['qq'] = $param['qq'];
//            }
//            if (isset($param['nickname']) && !empty($param['nickname'])) {
//                $data['nickname'] = $param['nickname'];
//            }
//            if (isset($param['sex']) && !empty($param['sex'])) {
//                $data['sex'] = $param['sex'];
//            }
//            if (isset($param['birthday']) && !empty($param['birthday'])) {
//                $data['birthday'] = $param['birthday'];
//            }
//            if (isset($param['headimgurl']) && !empty($param['headimgurl'])) {
//                $data['headimgurl'] = $param['headimgurl'];
//            }
//
//            if (empty($data)) {
//                self::$err_code = 400071;
//                throw new \Exception('FAULT');
//            }
//            if ($user_data) {
//                // 数据已存在  编辑
//                Db::table('mob_member_role_info')->where($where)->update($data);
//            } else {
//                // 数据不存在  新增
//                $data = array_merge_recursive($data, $where); // 将用户ID和类型合并到插入的数据中
//                Db::table('mob_member_role_info')->insert($data);
//            }
//
//            Db::commit();
//            return ['code' => 200, 'msg' => 'SUCCESS'];
//
//        } catch (\Exception $e) {
//            // 回滚事务
//            Db::rollback();
//            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
//        }
//    }

    // 验证安全密码
    static public function check_safe_password($param) {
        if(!isset($param['member_id']) || !isset($param['safe_password'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        $member_id = $param['member_id'];
        // 解密数据
        $des = new DES3();
        $safe_password = $des->decrypt($param['safe_password']);
        try{
            $time = strtotime(date('Y-m-d'));
            $error_count = db('safe_password_error_log')->where('member_id', $member_id)->where('add_time', '> time', $time)->count();
            if ($error_count >= 3) {
                self::$err_code = 400123;
                throw new \Exception('FAULT');
            }
            
            $member_safe_password = db('member')->where('id', $member_id)->value('safe_password');
            if (!$member_safe_password) {
                self::$err_code = 400080;
                throw new \Exception('FAULT');
            }

            if (md5($safe_password) != $member_safe_password) {
                // 增加错误记录
                $error_data = [
                    'member_id' => $member_id,
                    'add_time' => time()
                ];
                db('safe_password_error_log')->insert($error_data);
                if ($error_count == 0) {  // 第一次错误
                    self::$err_code = 400120;
                    throw new \Exception('FAULT');
                }
                if ($error_count == 1) { // 第二次错误
                    self::$err_code = 400121;
                    throw new \Exception('FAULT');
                }
                if ($error_count == 2) { // 第三次错误
                    self::$err_code = 400122;
                    throw new \Exception('FAULT');
                }
                self::$err_code = 400081;
                throw new \Exception('FAULT');
            }
            // 验证成功 删除当天错误记录
            db('safe_password_error_log')->where('member_id', $member_id)->delete();
            
        } catch (\Exception $e) {
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        };
        return ['code' => 200, 'msg' => '验证成功'];
    }

    // 加盟咨询
    static public function league_consult ($param)
    {
        if(!isset($param['name']) || !isset($param['phone']) || !isset($param['area'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try {
            db('league_consult')->insert($param);
            return ['code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => 'FAULT'];
        }
    }
}
